class BackupsController < ApplicationController
  before_filter :login_required

  def index
    @backups = current_user.backups
  end

  def create
    params[:backup] ||= {}
    params[:backup][:type] ||= params[:backup_type] # problem with a field name, no biggie!

    # MOVE THIS LOGIC INTO THE MODEL, somehow?
    backup_class = params[:backup][:type] || 'Backup'
    backup_class += 'Backup' unless backup_class.include?'Backup' # <--- icky!
    backup_class = backup_class.constantize

    @backup = backup_class.new params[:backup].merge({ :user => current_user })
    # @backup = backup_class.new :user => current_user, :username => 'foo'

    if @backup.save
      redirect_to backups_path
    else
      @backups = current_user.backups
      render :action => :index
      # redirect_to backups_path
    end
  end

  def run
    @backup = Backup.find params[:id]
    begin
      @backup.run
      flash[:notice] = "Backup ran successfully"
    rescue Exception => ex
      flash[:notice] = "Backup failed!  #{ ex.to_yaml }"
    end
    redirect_to backups_path
  end

  def plugin_attributes
    @plugin = ( params[:plugin].to_s + "Backup" ).constantize
  end

end
